package js.web.center.utils;

public class JsWebHexBinUtils {
	/**
	 * 2進制轉16進制
	 * @param binStr
	 * @return
	 */
	public static String bin2Hex(String binStr) {
		StringBuffer temp = null;
		while (binStr.length() % 4 != 0) {
			temp = new StringBuffer(binStr);
			temp.insert(0, "0");
			binStr = temp.toString();
		}
		StringBuffer sb = new StringBuffer();
		int deci = 0;
		for (int i = 0; i <= binStr.length() - 4; i += 4) {
			deci = Integer.valueOf(binStr.substring(i, i + 4), 2);
			sb.append(Integer.toHexString(deci));
		}
		return sb.toString();
	}
	/**
	 * 16進制轉2進制
	 * @param hexStr
	 * @return
	 */
	public static String hex2Bin(String hexStr) {
		StringBuffer sb = new StringBuffer();
		int deci = 0;
		StringBuffer temp = null;
		for (int i = 0; i < hexStr.length(); i++) {
			deci = Integer.valueOf(hexStr.charAt(i) + "", 16);
			temp = new StringBuffer(Integer.toBinaryString(deci));
			while (temp.length() < 4) {
				temp.insert(0, "0");
			}
			sb.append(temp);
		}
		return sb.toString();
	}
}
